<template>
  <div class="asset-list">
    <el-row>
      <el-col :span="3">
        <!-- 搜索 -->
        <el-input
            v-model="assetStore.queryParams.assetName"
            placeholder="请输入资产名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 300px; margin-bottom: 20px;"
        ></el-input>
      </el-col>
      <el-col :span="3"></el-col>
      <el-col :span="3" :offset="1">
        <el-select
            v-model="assetStore.queryParams.categoryName"
            placeholder="请选择类别"
            clearable
        >
          <el-option label="工具" value="1"/>
          <el-option label="设备" value="2"/>
          <el-option label="耗材" value="3"/>
        </el-select>
      </el-col>
      <el-col :span="3" :offset="1">
        <el-select
            v-model="assetStore.queryParams.statusName"
            placeholder="请选择状态"
            clearable
        >
          <el-option label="在库" value="1"/>
          <el-option label="借出" value="2"/>
          <el-option label="维修" value="3"/>
          <el-option label="出库" value="4"/>
        </el-select>
      </el-col>
      <el-col :span="3" :offset="1">
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
    </el-row>
    <!-- 资产列表 -->
    <el-table
        v-loading="loading"
        :data="assetList"
        style="width: 100%; text-align: center"
        border
    >
      <el-table-column prop="assetName" label="资产名称" width="180" align="center"/>
      <el-table-column prop="categoryName" label="资产分类" width="180" align="center"/>
      <el-table-column prop="assetType" label="资产类型" align="center"/>
      <el-table-column prop="stockQuantity" label="数量" width="80" align="center"/>
      <el-table-column prop="statusName" label="状态" width="100" align="center"/>
      <el-table-column prop="location" label="存放地点" align="center"/>
      <el-table-column prop="description" label="描述" align="center"/>
      <!-- 操作列 -->
      <el-table-column label="操作" width="100" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleBorrow(scope.row)">借用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="assetStore.queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="assetStore.queryParams.page"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          style="margin: 0 auto"
      />
    </div>

    <!-- 借用对话框 -->
    <el-dialog v-model="dialogVisible" title="借用资产" style="width: 600px">
      <el-form :model="borrowForm" label-width="120px" :rules="borrowRules" ref="borrowFormRef">
        <el-form-item label="资产ID">
          <el-input v-model="borrowForm.assetId" disabled/>
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="borrowForm.assetName" disabled/>
        </el-form-item>
        <el-form-item label="借用数量" prop="quantity">
          <el-input v-model.number="borrowForm.quantity" placeholder="请输入借用数量"/>
        </el-form-item>
        <el-form-item label="预计归还时间" prop="expectedReturnTime">
          <el-date-picker
              v-model="borrowForm.expectedReturnTime"
              type="datetime"
              placeholder="选择预计归还时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="defaultTime"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBorrow">确定借用</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, onMounted, computed, reactive} from 'vue';
import {useAssetStore} from '@/stores/user/asset.js';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';
import {useBorrowStore} from "@/stores/user/borrow";

const router = useRouter();
const assetStore = useAssetStore();
const borrowStore = useBorrowStore();


// 获取状态
const assetList = computed(() => assetStore.assetList);
const total = computed(() => assetStore.total);
const loading = computed(() => assetStore.loading);

//禁用所有今天之前的日期
const disabledDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date < today;
};

// 设置默认时间为当前时间
const defaultTime = ref(new Date());

// 对话框相关
const dialogVisible = ref(false);
const borrowForm = reactive({
  assetId: null,
  assetName: null,
  quantity: 1, // 默认借用数量
  expectedReturnTime: null,
});

const borrowFormRef = ref(null); // 获取表单实例

const borrowRules = reactive({
  quantity: [
    {required: true, message: '请输入借用数量', trigger: 'blur'},
    {type: 'number', min: 1, message: '借用数量必须大于 0', trigger: 'blur'},
  ],
  expectedReturnTime: [
    {required: true, message: '请选择预计归还时间', trigger: 'change'},
  ],
});

// 监听页码变化
const handleCurrentChange = (page) => {
  assetStore.setPage(page);
  assetStore.getAssets();
};

// 监听页尺寸变化
const handleSizeChange = (PageSize) => {
  assetStore.setPageSize(PageSize);
  assetStore.getAssets();
};

// 搜索
const handleSearch = () => {
  assetStore.queryParams.page = 1; // 搜索时重置为第一页
  assetStore.getAssets();
};

// 重置
const handleReset = () => {
  assetStore.resetQuery();
  assetStore.getAssets()
}

// 点击借用按钮
const handleBorrow = (row) => {
  borrowForm.assetId = row.assetId;
  borrowForm.assetName = row.assetName;
  dialogVisible.value = true;
};

// 提交借用申请
const submitBorrow = async () => {
  borrowFormRef.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过
      const success = await borrowStore.borrowAsset(borrowForm);
      if (success) {
        ElMessage.success('借用申请提交成功');
        assetStore.getAssets();
        dialogVisible.value = false;
        // 可以选择刷新资产列表，或者跳转到借用记录页面
        //router.push('/user/borrow'); // 跳转到借用页面
      }
    } else {
      // 表单验证失败
      console.log('表单验证失败');
      return false;
    }
  });
};

onMounted(() => {
  assetStore.getAssets();
});
</script>
<style scoped>
.asset-list {
  padding: 20px;
}
</style>